const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { ApiResponse } = require('@shared/utils/response');

// 配置文件路径
const CONFIG_FILE_PATH = path.join(__dirname, '../../../config/system-settings.json');

// 确保配置文件存在
const ensureConfigFile = () => {
  if (!fs.existsSync(CONFIG_FILE_PATH)) {
    const defaultConfig = {
      siteName: '商城系统',
      logo: '',
      phone: '',
      email: '',
      address: '',
      icp: ''
    };
    
    // 确保目录存在
    const configDir = path.dirname(CONFIG_FILE_PATH);
    if (!fs.existsSync(configDir)) {
      fs.mkdirSync(configDir, { recursive: true });
    }
    
    fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(defaultConfig, null, 2));
    return defaultConfig;
  }
  
  return JSON.parse(fs.readFileSync(CONFIG_FILE_PATH, 'utf8'));
};

// 获取系统配置
router.get('/config', (req, res) => {
  try {
    const config = ensureConfigFile();
    res.json(ApiResponse.success(config));
  } catch (error) {
    console.error('获取系统配置失败:', error);
    res.status(500).json(ApiResponse.error('获取系统配置失败'));
  }
});

// 更新系统配置
router.put('/config', (req, res) => {
  try {
    const newConfig = req.body;
    
    // 获取当前配置
    const currentConfig = ensureConfigFile();
    
    // 合并配置
    const updatedConfig = {
      ...currentConfig,
      ...newConfig
    };
    
    // 写入配置文件
    fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(updatedConfig, null, 2));
    
    res.json(ApiResponse.success(updatedConfig));
  } catch (error) {
    console.error('更新系统配置失败:', error);
    res.status(500).json(ApiResponse.error('更新系统配置失败'));
  }
});

module.exports = router; 